//
//  editVideoViewController.m
//  BigRaindrop
//
//  Created by whlx on 2019/1/4.
//  Copyright © 2019 TxY. All rights reserved.
//

#import "editVideoViewController.h"
#import "NvTimelineUtils.h"
#import "NvSDKUtils.h"
#import "NvLiveWindowPanelView.h"
#import "NvFeatureItem.h"
#import "NvFeatureCollectionViewCell.h"
#import "NvEditCaptionViewController.h"

@interface editVideoViewController ()<UICollectionViewDataSource, UICollectionViewDelegate,NvLiveWindowPanelViewDelegate>{
    
    NvsStreamingContext *_streamingContext;
    NvsTimeline *_timeline;
    NvTimelineData *_timelineData;
    NvLiveWindowPanelView *_liveWindowPanelView;
    UICollectionView *_featureCollectionView;
    NSMutableArray *_featureDataSource;
}

@end

@implementation editVideoViewController



- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [NvTimelineUtils recreateTimeline:_timeline];
    [self connectTimeline];
    [_liveWindowPanelView playAtTime:0];
    [_liveWindowPanelView showControllPanel];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.navigationItem.title = @"视频彩铃制作";
    self.edgesForExtendedLayout = UIRectEdgeNone;
    
    self.view.backgroundColor = [UIColor blackColor];
    _streamingContext = [NvSDKUtils getSDKContext];
    [self initView];
    [self initTimeline];
    [self initTimelineData];
}


- (IBAction)addText:(id)sender {
    
    NvTimelineData *data = [NvTimelineData sharedInstance];
    NSMutableArray *arr = [NSMutableArray array];
    
    NvCaptionInfoModel *model = [NvCaptionInfoModel new];
    model.category = NvsDefaultCategory;
    model.roleInTheme = NvsRoleInThemeGeneral;
    model.alignment = NvsTextAlignmentLeft;
    model.isBold = YES;
    model.text = @"测试测试";
//  model.fontSize = 100;
    model.color = [UIColor redColor];
    model.rotation = 0;
    model.scale = 0.5;
//    model.uuid = @"B1F16660-FB3F-4E74-AD8D-54ADE73F657F";
    model.inPoint = 0;
    model.outPoint = 5*NV_TIME_BASE;
    model.anchorPoint = CGPointMake(0, 0);
    model.translation = CGPointMake(0, 0);
    [arr addObject:model];
    
    data.captionDataArray = arr;
    NSMutableArray *order = [[NvTimelineData sharedInstance] dataOrder];
    [order removeObject:@"Caption"];
    [order addObject:@"Caption"];
    [self viewWillAppear:YES];
}

- (IBAction)addImage:(id)sender {
    
    NSURL*url=  [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"timg" ofType:@"jpeg"]];
    NvStickerInfoModel *model = [NvStickerInfoModel new];
    model.isCustomSticer = NO;
    model.isSlient=YES;
    model.rotation = 0;
    model.scale = 0.3;
    //    model.uuid = @"A005E548-EE2E-4504-9A2E-5FC286DFBA1C";
    model.packageId =@"E14FEE65-71A0-4717-9D66-3397B6C11223";
    // _packageId    __NSCFString *    @"E14FEE65-71A0-4717-9D66-3397B6C11223"    0x00000002819f8380
    model.customImagePath =url.absoluteString;
    //    url.absoluteString;
    model.inPoint = 0;
    model.outPoint = 5*NV_TIME_BASE;
    model.volume =0 ;
    model.anchor = CGPointMake(0, 0);
    model.translation = CGPointMake(0, 0);
    NSMutableArray *arrM = [NSMutableArray array];
    [arrM addObject:model];
    NvTimelineData *data = [NvTimelineData sharedInstance];
    data.stickerDataArray = arrM;
    
    NSMutableArray *order = [[NvTimelineData sharedInstance] dataOrder];
    [order removeObject:@"Sticker"];
    [order addObject:@"Sticker"];
    
    [self viewWillAppear:YES];
    
}


-(void)initView{
    
    _liveWindowPanelView = [[NvLiveWindowPanelView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 210)];
    _liveWindowPanelView.editMode = NvEditMode16v9;
    _liveWindowPanelView.delegate = self;
    [self.view addSubview:_liveWindowPanelView];
    
     _featureDataSource = [[NSMutableArray alloc] init];
    NSArray *featureNameArray = @[@"主播配音", @"背景音乐", @"文字", @"贴纸", @"图片", @"主题", @"滤镜"];
    
    NSArray *featureImageArray = @[@"NvEditTheme", @"NvEditTheme", @"NvEditTheme", @"NvEditTheme", @"NvEditTheme", @"NvEditTheme", @"NvEditTheme"];
    
    for (int i = 0; i < featureNameArray.count; i++) {
        NvFeatureItem *item = [NvFeatureItem new];
        item.name = featureNameArray[i];
        item.image = featureImageArray[i];
        [_featureDataSource addObject:item];
    }
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    layout.itemSize = CGSizeMake(73 * SCREANSCALE, 78 * SCREANSCALE);
    layout.minimumLineSpacing = 3 * SCREANSCALE;
    layout.minimumInteritemSpacing = 0;
    //layout.sectionInset = UIEdgeInsetsMake(0, 16*SCREANSCALE, 0, 0);
    
    
    _featureCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(_liveWindowPanelView.frame)+10, self.view.width, 200) collectionViewLayout:layout];
    
//    _featureCollectionView.backgroundColor = [UIColor redColor];
    _featureCollectionView.delegate = self;
    _featureCollectionView.dataSource = self;
    _featureCollectionView.backgroundColor = [UIColor clearColor];
    _featureCollectionView.showsHorizontalScrollIndicator = NO;
    
    
    
    [_featureCollectionView registerClass:[NvFeatureCollectionViewCell class] forCellWithReuseIdentifier:@"NvFeatureCollectionViewCell"];
    [self.view addSubview:_featureCollectionView];

}

#pragma mark - UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _featureDataSource.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    NvFeatureCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"NvFeatureCollectionViewCell" forIndexPath:indexPath];
    [cell renderCellWithItem:_featureDataSource[indexPath.row]];

    return cell;
//    return  [UICollectionViewCell new];
}

#pragma mark - UICollectionViewDelegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    [_streamingContext stop];
    
    NvFeatureItem *item = _featureDataSource[indexPath.row];
    if ([item.name isEqualToString:@"主题"]) {
//        NvEditThemeViewController *vc = [[NvEditThemeViewController alloc]init];
//        vc.timeline = _timeline;
//        vc.editMode = self.editMode;
//        vc.delegate = self;
//        vc.title = @"主题";
//        [self.navigationController pushViewController:vc animated:YES];
    }else if ([item.name isEqualToString:@"编辑"]) {
//        NvEditMaterialViewController *vc = [[NvEditMaterialViewController alloc]init];
//        //        vc.timeline = _timeline;
//        vc.editMode = self.editMode;
//        vc.delegate = self;
//        [self.navigationController pushViewController:vc animated:YES];
        
    } else if ([item.name isEqualToString:@"文字"]) {
        
//        NvEditCaptionViewController *captionVC = [NvEditCaptionViewController new];
//        captionVC.editMode =NvEditMode16v9;
//        [self.navigationController pushViewController:captionVC animated:YES];

    }
  
}

- (void)backBtnClicked{
    [[NvTimelineData sharedInstance] clear];
    [NvTimelineUtils removeTimeline:_timeline];
}


- (void)connectTimeline {
//    [_liveWindowPanelView connectTimeline:_timeline];
//    _liveWindowPanelView.currentTime = 0;
    [self seekTimeline:0];
}

- (void)seekTimeline:(int64_t)postion {
    if (![_streamingContext seekTimeline:_timeline timestamp:postion videoSizeMode:NvsVideoPreviewSizeModeLiveWindowSize flags:NvsStreamingEngineSeekFlag_ShowCaptionPoster | NvsStreamingEngineSeekFlag_ShowAnimatedStickerPoster])
        NSLog(@"定位时间线失败！");
}


- (void)initTimeline {
    _timeline = [NvTimelineUtils createTimeline:NvEditMode16v9];
    if (!_timeline) {
        NSLog(@"创建时间线失败！");
        return;
    }
}

- (void)initTimelineData {
    _timelineData = [NvTimelineData sharedInstance];
  
//    NSString *path = self.videoPath;
//    AVURLAsset*audioAsset=[AVURLAsset URLAssetWithURL:[NSURL fileURLWithPath:path] options:nil];
//    editData.trimOut = audioAsset.duration.value/(float)audioAsset.duration.timescale*NV_TIME_BASE;
//    editData.isImage = NO;
//    editData.videoPath = path;
//
//    editData.trimIn = 0;
//    editData.duration = editData.trimOut;
//    [timelineData.editDataArray addObject:editData];
//
//    NvTransitionInfoModel *info = NvTransitionInfoModel.new;
//    [[[NvTimelineData sharedInstance] transitionDataArray] addObject:info];
    
    
    PHVideoRequestOptions *options = [[PHVideoRequestOptions alloc] init];
    options.version = PHVideoRequestOptionsVersionOriginal;
    options.deliveryMode = PHVideoRequestOptionsDeliveryModeAutomatic;
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
    
    NSString *path = self.videoPath;
    AVURLAsset*audioAsset=[AVURLAsset URLAssetWithURL:[NSURL fileURLWithPath:path] options:nil];
    
    NvEditDataModel *editData = NvEditDataModel.new;
//                editData.asset = asset.asset;
    
    editData.trimOut = audioAsset.duration.value/(float)audioAsset.duration.timescale*NV_TIME_BASE;
    editData.isImage = NO;
    editData.videoPath = path;
    
    editData.trimIn = 0;
//    editData.videoPath = path;
//    //     asset.asset.localIdentifier;
//    editData.isImage = NO;
//    editData.trimIn = 0;
//    editData.trimOut = 190/(float)10.0*NV_TIME_BASE;
    editData.duration = editData.trimOut;
    [_timelineData.editDataArray addObject:editData];
    NvTransitionInfoModel *info = NvTransitionInfoModel.new;
    [[[NvTimelineData sharedInstance] transitionDataArray] addObject:info];
    dispatch_semaphore_signal(semaphore);
    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
    
    
}



#pragma mark - NvLiveWindowPanelViewDelegate
- (void)volumnClicked {
//    _originSoundView.hidden = NO;
    
    [self.navigationController setNavigationBarHidden:YES];
}


@end
